package com.maolei.jeecg.chapter6.generator.core.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.maolei.jeecg.chapter6.generator.core.model.Column;
import com.maolei.jeecg.chapter6.generator.core.model.Table;

public class MetaDataUtil {
	private Connection con;

	public Table getTables(String _tableName) {
		con = DBUtil.getConnection();
		ResultSet tableRs = null;
		try {
			tableRs = con.getMetaData().getTables(null, null, _tableName, null);
			while (tableRs.next()) {
				Table table = createTable(tableRs);
				return table;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.closeAll(con, null, tableRs);
		}
		return null;
	}

	public List<Table> getAllTables() {
		con = DBUtil.getConnection();
		ResultSet tableRs = null;
		try {
			tableRs = con.getMetaData().getTables(null, null, null, null);
			List<Table> tables = new ArrayList<Table>();
			while (tableRs.next()) {
				Table table = createTable(tableRs);
				tables.add(table);
			}
			return tables;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.closeAll(con, null, tableRs);
		}
		return null;
	}

	private Table createTable(ResultSet tableRs) throws SQLException {
		String tableName = tableRs.getString("TABLE_NAME");
		String tableType = tableRs.getString("TABLE_TYPE");
		Table table = new Table(tableName, tableType);
		getColumns(table);
		return table;
	}

	private void getColumns(Table table) {
		con = DBUtil.getConnection();
		ResultSet columnRs = null;
		try {
			columnRs = con.getMetaData().getColumns(null, null, table.getTableName(), null);
			while (columnRs.next()) {
				String columnName = columnRs.getString("COLUMN_NAME");
				String typeName = columnRs.getString("TYPE_NAME");
				int dataType = columnRs.getInt("DATA_TYPE");
				int columnSize = columnRs.getInt("COLUMN_SIZE");
				int decimalDigits = columnRs.getInt("DECIMAL_DIGITS");
				String remarks = columnRs.getString("REMARKS");
				Column column = new Column(columnName, typeName, dataType, columnSize, decimalDigits, remarks);
				table.addColumn(column);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.closeAll(con, null, columnRs);
		}
	}

	public static void main(String[] args) {
		MetaDataUtil dao = new MetaDataUtil();
		// System.out.println(JSON.toJSONString(dao.getTables("fault")));
		System.out.println(JSON.toJSONString(dao.getAllTables()));
	}

}
